// console.log(el, binding, vnode)
// 传入的模式 press swipeRight swipeLeft swipeTop swipeDowm Tap

import eventBus from "./eventBus"

var direction = ''
// 滑动处理
var startX, startY

let root = null
const inputList = ['INPUT', 'TEXTAREA']

// 返回角度
function GetSlideAngle(dx, dy) {
  return Math.atan2(dy, dx) * 180 / Math.PI
}

// 根据起点和终点返回方向 1：向上，2：向下，3：向左，4：向右,0：未滑动
function GetSlideDirection(startX, startY, endX, endY) {
  var dy = startY - endY
  var dx = endX - startX
  var result = 0

  // 如果滑动距离太短
  if (Math.abs(dx) < 28 && Math.abs(dy) < 28) {
    return result
  }
  var angle = GetSlideAngle(dx, dy)

  if (angle >= -45 && angle < 45) {
    result = 'swiperight'
  } else if (angle >= 45 && angle < 135) {
    result = 'swipeup'
  } else if (angle >= -135 && angle < -45) {
    result = 'swipedown'
  } else if ((angle >= 135 && angle <= 180) || (angle >= -180 && angle < -135)) {
    result = 'swipeleft'
  }
  return result
}





export function mouseDownEvent(ev) {
  // 在输入框的滑动，不触发（
  if (inputList.includes(ev.target.nodeName)) {

    return
  }

  startX = ev.pageX
  startY = ev.pageY

  document.addEventListener('mouseup', mouseUpEvent, false)
}

function mouseUpEvent(ev) {
  var endX, endY
  endX = ev.pageX
  endY = ev.pageY
  direction = GetSlideDirection(startX, startY, endX, endY)

  document.removeEventListener('mouseup', mouseUpEvent)
  eventBus.emit('touch', direction)

}


export function addTouchEvent(pageDiv) {

  root = pageDiv.current
  root.addEventListener('mousedown', mouseDownEvent, false)
}
export function reomveTouchEvent() {

  root.removeEventListener('mousedown', mouseDownEvent)
  root = null
}